<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\helpers\MyCodeService;
use app\traits\JsonResponse;
use think\exception\ValidateException;
use think\facade\Request as RequestFacade;
use think\Request;
use app\model\Cat as CatModel;

class Cat extends BaseController {
    use JsonResponse;
    protected $middleware = [
        'auth_jwt' => ['only' => ['save','update','delete']],
    ];
    public function index() {
        $cats = CatModel::order('sort','asc')->select();
        return $this->jsonSuccess($cats);
    }

    public function save(Request $request,CatModel $cat) {
        if(!isSuperAdmin($this->user_id)) return $this->jsonFail(message:'非超级管理员不能操作');
        try {
            validate([
                'title|帖子大类的名称'  => 'require|max:255|unique:cat',
                'sort|排序'    => 'integer|egt:0'
            ])->batch()->check($request->post());
              $sort = $request->post('sort') ?? 1;
              $cat->sort = $sort;
              $cat->title = $request->post('title');
              $cat->save();
            return $this->jsonSuccess($cat,'帖子大类添加成功',201);
        } catch (ValidateException $e) {
            return $this->jsonFail($e->getError(),'输入信息不合法',422);
        }
    }

    public function read($id) {
        $cat = CatModel::findOrEmpty($id);
        if(!$cat->isEmpty()){
            return $this->jsonSuccess($cat);
        }else{
            return $this->jsonFail();
        }
    }

    public function update(Request $request, $id) {
        if(!isSuperAdmin($this->user_id)) return $this->jsonFail(message:'非超级管理员不能操作');
        try {
            validate([
                'title|帖子大类的名称'  => 'require|max:255|unique:cat,title,'.$id,
                'sort|验证码'    => 'integer|egt:0'
            ])->batch()->check($request->post());
            $cat = CatModel::findOrEmpty($id);
            if(!$cat->isEmpty()){
                $sort = $request->post('sort') ?? 1;
                $cat->sort = $sort;
                $cat->title = $request->post('title');
                $cat->save();
                return $this->jsonSuccess($cat,'帖子大类添加成功');
            }else{
                return $this->jsonFail();
            }

        } catch (ValidateException $e) {
            return $this->jsonFail($e->getError(),'输入信息不合法',422);
        }
    }

    public function delete($id) {
        if(!isSuperAdmin($this->user_id)) return $this->jsonFail(message:'非超级管理员不能操作');
        $cat = CatModel::findOrEmpty($id);
        if(!$cat->isEmpty()){
            $cat->delete();
            return $this->jsonSuccess([],'帖子大类删除成功');
        }else{
            return $this->jsonFail();
        }
    }
}
